package com.hundsun.yr.universal.p2p.presenter.impl;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.base.BaseAppManager;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.library.widget.HSToast;
import com.hundsun.yr.universal.p2p.bean.AdSlideBeen;
import com.hundsun.yr.universal.p2p.bean.BeforeInvestBean;
import com.hundsun.yr.universal.p2p.bean.DiscountBeen;
import com.hundsun.yr.universal.p2p.bean.InvestProtocolBean;
import com.hundsun.yr.universal.p2p.bean.UpdatePayPwdBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.interactor.base.RequestInteractor;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestGetInteractorImpl;
import com.hundsun.yr.universal.p2p.interactor.impl.StringRequestInteractorImpl;
import com.hundsun.yr.universal.p2p.listener.BaseMultiLoadedListener;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.ui.activity.InvestActivity;
import com.hundsun.yr.universal.p2p.ui.activity.MineInvestActivity;
import com.hundsun.yr.universal.p2p.utils.AndroidDes3Util;
import com.hundsun.yr.universal.p2p.utils.GsonTool;
import com.hundsun.yr.universal.p2p.utils.Logs;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;

import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;

import de.greenrobot.event.EventBus;


/**
 * @version V1.0
 * @Title: InitializePresenterImpl.java
 * @Description: TODO(用一句话描述该文件做什么)
 * @date 2015-10-27 上午11:18:59
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class InitializeTargetPresenterImpl implements RequestPresenter, BaseMultiLoadedListener<String>, OnClickListener {

    private Context mContext = null;
    private InitializeView mView = null;
    private RequestInteractor mInteractor = null;
    private RequestInteractor mInteractor2 = null;
    /**
     * 任务名
     **/
    private String mTask_name;
    /**
     * 请求地址
     **/
    private String mUrl;
    /**
     * 加载事件
     **/
    private int mEvent_tag;
    /**
     * 参数
     **/
    private HashMap<String, String> mParams;
    /**
     * 是否刷新
     **/
    private boolean mIsSwipeRefresh;
    /**
     * 用户sp文件
     **/
    private HSSharedPreferences hsSharedPreferences = null;

    public InitializeTargetPresenterImpl(Context context, InitializeView view) {
        // TODO Auto-generated constructor stub
        if (null == view) {
            throw new IllegalArgumentException("Constructor's parameters must not be Null");
        }
        this.mContext = context;
        this.mView = view;
        this.mInteractor = new StringRequestInteractorImpl(this);
        this.mInteractor2 = new StringRequestGetInteractorImpl(this);
        this.hsSharedPreferences = new HSSharedPreferences(context, Config.SPPath.file_userLoginedInfo);
    }

    @Override
    public void onSuccess(String task_name, int event_tag, String data) {
        try {
            AdSlideBeen adSlideBeen = (AdSlideBeen) GsonTool.getInstanceByJson(AdSlideBeen.class, data);
            if (adSlideBeen.code.equals(Constants.REQUESTCODE_100600)){
                hsSharedPreferences.putBoolean(UserInfo.ISLOGIN, false);
                EventBus.getDefault().post(new EventCenter(Constants.EVENT_DATA_LOGIN_EXPIRED));
            }

            switch (task_name) {
                case TaskConstants.TASK_INVEST://投资
                    switch (adSlideBeen.code) {
                        case Constants.REQUESTCODE_000000:
                            //投资按钮点击成功，准备投资
                            try {
                                String decode = AndroidDes3Util.decode(adSlideBeen.data, hsSharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                                mView.initializeViews(TaskConstants.TASK_INVEST, decode.substring(decode.indexOf("<")));
                            } catch (Exception e) {
                                new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error)).show();
                                e.printStackTrace();
                            }
                            break;
                        case Constants.REQUESTCODE_100500:
                            //验签错误
                            new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_overdue)).show();
                            break;
                        case Constants.REQUESTCODE_100020:
                            //Header值为空--不做任何提示
                            break;
                        case Constants.REQUESTCODE_100010:
                            break;
                        case Constants.REQUESTCODE_300329:
                            //未做风险评估
                            mView.initializeViews(TaskConstants.TASK_INVEST, adSlideBeen.code);
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            break;
                        case Constants.REQUESTCODE_300314:
                            //后台提示余额不足
                            mView.initializeViews(TaskConstants.TASK_INVEST, adSlideBeen.code);
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            break;
                        case Constants.REQUESTCODE_300304:
                            //有未支付订单
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            mContext.startActivity(new Intent(mContext, MineInvestActivity.class));
                            if (InvestActivity.class != null) {
                                BaseAppManager.getInstance().getActivity(InvestActivity.class).finish();
                            }
                            break;
                        default:
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            break;
                    }
                    break;

                case TaskConstants.TASK_DISCOUNT:
                    //优惠卷
                    switch (adSlideBeen.code) {
                        case Constants.REQUESTCODE_000000:
                            //网络访问成功
                            try {
                                String decode = AndroidDes3Util.decode(adSlideBeen.data, hsSharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                                String[] split = decode.split("\\n");
                                DiscountBeen discountBeen = (DiscountBeen) GsonTool.getInstanceByJson(DiscountBeen.class, split[1]);
                                mView.initializeViews(TaskConstants.TASK_DISCOUNT, discountBeen);

                            } catch (Exception e) {
                                new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error) + e.toString()).show();
                                e.printStackTrace();
                            }
                            break;
                        case Constants.REQUESTCODE_100500:
                            mView.initializeError(TaskConstants.TASK_DISCOUNT, "");
                            new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_overdue)).show();
                            break;
                        case Constants.REQUESTCODE_100600:
                            mView.initializeError(TaskConstants.TASK_DISCOUNT, "");
                            new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_overdue)).show();
                            break;
                        case Constants.REQUESTCODE_100020:
                            mView.initializeError(TaskConstants.TASK_DISCOUNT, "");
                            //Header值为空--不做任何提示
                            break;
                        case Constants.REQUESTCODE_100010:
                            mView.initializeError(TaskConstants.TASK_DISCOUNT, "");
                            break;
                        default:
                            mView.initializeError(TaskConstants.TASK_DISCOUNT, "");
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            break;
                    }
                    break;

                case TaskConstants.TASK_PROTOCOL://投资协议
                    switch (adSlideBeen.code) {
                        case Constants.REQUESTCODE_000000:
                            //网络访问成功
                            try {
                                String decode = AndroidDes3Util.decode(adSlideBeen.data, hsSharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                                String[] split = decode.split("\\n");
                                InvestProtocolBean instanceByJson = (InvestProtocolBean) GsonTool.getInstanceByJson(InvestProtocolBean.class, split[1]);
                                mView.initializeViews(TaskConstants.TASK_PROTOCOL, instanceByJson);
                            } catch (Exception e) {
                                new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error)).show();
                                e.printStackTrace();
                            }
                            break;
                        case Constants.REQUESTCODE_100500:
                            new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_overdue)).show();
                            break;
                        case Constants.REQUESTCODE_100020:
                            //Header值为空--不做任何提示
                            break;
                        case Constants.REQUESTCODE_100010:
                            break;
                        default:
                            mView.initializeError(TaskConstants.TASK_DISCOUNT, data);
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            break;
                    }
                    break;


                case TaskConstants.TASK_SETBANKPWD://设置修改交易密码
                    switch (adSlideBeen.code) {
                        case Constants.REQUESTCODE_000000:
                            try {
                                String decode3 = AndroidDes3Util.decode(adSlideBeen.data, hsSharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                                String[] split3 = decode3.split("\\n");
                                UpdatePayPwdBeen mUpdatePayPwdBeen = (UpdatePayPwdBeen) GsonTool.getInstanceByJson(UpdatePayPwdBeen.class, split3[1]);
                                mView.initializeViews(TaskConstants.TASK_SETBANKPWD, mUpdatePayPwdBeen);
                            } catch (Exception e) {
                                e.printStackTrace();
//								new HSToast(mContext).showToast(mContext.getString(R.string.date_error) +  e.toString());
                            }
                            break;
                        case Constants.REQUESTCODE_100500:
                            //验签错误重新登录
                            new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_overdue)).show();
                            break;
                        case Constants.REQUESTCODE_100020:
                            break;
                        case Constants.REQUESTCODE_100010:
                            break;
                        default:
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            break;
                    }
                    break;

                case TaskConstants.TASK_BEFOREINVEST://投资之前
                    switch (adSlideBeen.code) {
                        case Constants.REQUESTCODE_000000:
                            try {
                                String decode3 = AndroidDes3Util.decode(adSlideBeen.data, hsSharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), (Date.parse(adSlideBeen.timestamp) + "").substring((Date.parse(adSlideBeen.timestamp) + "").length() - 8, (Date.parse(adSlideBeen.timestamp) + "").length()));
                                String[] split3 = decode3.split("\\n");
//                                Logs.e("xushunzhen" + split3[1]);
                                BeforeInvestBean beforeInvestBean = (BeforeInvestBean) GsonTool.getInstanceByJson(BeforeInvestBean.class, split3[1]);
                                mView.initializeViews(TaskConstants.TASK_BEFOREINVEST, beforeInvestBean);
                            } catch (Exception e) {
                                e.printStackTrace();
//								new HSToast(mContext).showToast(mContext.getString(R.string.date_error) +  e.toString());
                            }
                            break;
                        case Constants.REQUESTCODE_100500:
                            mView.initializeError(TaskConstants.TASK_BEFOREINVEST, "");
                            //验签错误重新登录
                            new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.login_overdue)).show();
                            break;
                        case Constants.REQUESTCODE_100020:
                            mView.initializeError(TaskConstants.TASK_BEFOREINVEST, "");
                            break;
                        case Constants.REQUESTCODE_100010:
                            mView.initializeError(TaskConstants.TASK_BEFOREINVEST, "");
                            break;
                        default:
                            mView.initializeError(TaskConstants.TASK_BEFOREINVEST, "");
                            new HSToast(mContext).getSingleLongToast(adSlideBeen.msg).show();
                            break;
                    }
                    break;
            }
        } catch (Exception e) {
            new HSToast(mContext).getSingleLongToast(mContext.getString(R.string.date_error)).show();
            e.printStackTrace();
        }
        mView.closeProgress();
        mView.hideLoading();
    }


    @Override
    public void onException(String task_name, String msg) {
        // TODO Auto-generated method stub
        new HSToast(mContext).showToast(msg);
        if (mEvent_tag == Constants.EVENT_REFRESH_DATA) {
            mView.hideLoading();
        }
        mView.initializeError(task_name, "");
        mView.closeProgress();
    }


    @Override
    public void loadingData(String task_name, String url, int event_tag,
                            HashMap<String, String> params, boolean isSwipeRefresh) {
        // TODO Auto-generated method stub

        if (event_tag == Constants.EVENT_REFRESH_DATA) {
            this.mTask_name = task_name;
            this.mUrl = url;
            this.mParams = params;
            this.mIsSwipeRefresh = isSwipeRefresh;
            this.mEvent_tag = event_tag;
            mView.hideLoading();
        }
        if (NetUtils.isNetworkConnected(mContext)) {

            if (isSwipeRefresh) {
                if (event_tag == Constants.EVENT_REFRESH_DATA) {
                    mView.showLoading(mContext.getString(R.string.common_loading_message));
                } else {

                    mView.showProgress("");
                }
            }
            mInteractor.getRequestData(task_name, url, event_tag, params);

        } else {
            mView.closeProgress();
            mView.showNetError(this);
            mView.initializeError(task_name, R.string.common_no_network);
        }
    }

    @Override
    public void loadingData(String task_name, String url, int event_tag, HashMap<String, String> params, HashMap<String, String> header, boolean isSwipeRefresh) {
        if (NetUtils.isNetworkConnected(mContext)) {
            if (isSwipeRefresh) {
                if (event_tag == Constants.EVENT_REFRESH_DATA) {
                    mView.showLoading(mContext.getString(R.string.common_loading_message));
                } else {
                    mView.showProgress("");
                }
            }
            mInteractor2.getRequestData(task_name, url, event_tag, params, header);
        } else {
            mView.closeProgress();
            mView.showNetError(this);
            mView.initializeError(task_name, R.string.common_no_network);
        }
    }

    /**
     * json+header
     *
     * @param task_name
     * @param url
     * @param event_tag
     * @param params
     * @param header
     * @param isSwipeRefresh
     */
    @Override
    public void loadingData(String task_name, String url, int event_tag, JSONObject params, HashMap<String, String> header, boolean isSwipeRefresh) {
        //进行投资请求
        if (NetUtils.isNetworkConnected(mContext)) {
            if (isSwipeRefresh) {
                if (event_tag == Constants.EVENT_REFRESH_DATA) {
                    mView.showLoading(mContext.getString(R.string.common_loading_message));
                } else {

                    mView.showProgress("");
                }
            }
            mInteractor.getRequestData(task_name, url, event_tag, params, header);
        } else {
            mView.closeProgress();
            mView.showNetError(this);
            mView.initializeError(task_name, R.string.common_no_network);
        }

    }


    @Override
    public void initialized() {
        // TODO Auto-generated method stub
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        if (!NetUtils.isNetworkConnected(mContext)) {
            new HSToast(mContext).showToast(R.string.common_no_network);
            return;
        }

        mView.hideLoading();
        if (mIsSwipeRefresh) {
            mView.showLoading(mContext.getString(R.string.common_loading_message));
        }
        loadingData(mTask_name, mUrl, mEvent_tag, mParams, mIsSwipeRefresh);
    }

}
